package fr.emse.tatiana;



import java.util.List;
import java.util.Vector;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.registry.ActionSetRegistry;
import org.eclipse.ui.internal.registry.IActionSetDescriptor;


import fr.emse.tatiana.commands.*;
import fr.emse.tatiana.extensionprovider.IAnalysisActivator;
import fr.emse.tatiana.extensionprovider.IVisualisationActivator;
import fr.emse.tatiana.replayable.analysis.GraphAnalysisEditor;
import fr.emse.tatiana.replayable.tabulardisplay.ReplayableTabularEditor;
import fr.emse.tatiana.replayable.tabulardisplay.ReplayableTabularViewer;


/**
 * An action bar advisor is responsible for creating, adding, and disposing of the
 * actions added to a workbench window. Each window will be populated with
 * new actions.
 */
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
	
	public static List<IAction> navigationViewContingentActions = 
		new Vector<IAction>();
	public static List<IAction> replayableSelectedContingentActions = 
		new Vector<IAction>();

	public static ApplicationActionBarAdvisor instance;
	
    // Actions - important to allocate these only in makeActions, and then use them
    // in the fill methods.  This ensures that the actions aren't recreated
    // when fillActionBars is called with FILL_PROXY.
    private IWorkbenchAction exitAction;
    private IWorkbenchAction aboutAction;
    private IWorkbenchAction saveAction;
    private IWorkbenchAction saveAsAction;
    public Action addFileAction;
	public Action applyFilterAction;
	public Action createReplayableAction;
	public Action newCorpusAction;
	public Action deleteFileAction;
	public Action deleteCorpusAction;
	public Action createFolderAction;
	public Action renameFileAction;
	public List<IAction> newAnalysisActions;
	public Action newGraphAction;
	private Action openWithGraphicalAction;
	Action exportAction;
	Action importAction;
	public Vector<IAction> newVisualisationActions;
	private TatianaExportAction tatianaExportAction;
    
    @SuppressWarnings("restriction")
	public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
        super(configurer);
        instance = this;
        ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry();
        IActionSetDescriptor[] actionSets = reg.getActionSets();
        // removing annoying gotoLastPosition Message.
        String actionSetId = "org.eclipse.ui.edit.text.actionSet.navigation"; //$NON-NLS-1$
        for (int i = 0; i <actionSets.length; i++){
            if (!actionSets[i].getId().equals(actionSetId))
                continue;
                IExtension ext = actionSets[i].getConfigurationElement()
                    .getDeclaringExtension();
                reg.removeExtension(ext, new Object[] { actionSets[i] });
        }
        // Removing convert line delimiters menu.
        actionSetId = "org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo"; //$NON-NLS-1$
        for (int i = 0; i <actionSets.length; i++){
            if (!actionSets[i].getId().equals(actionSetId))
                continue;
            IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension();
           reg.removeExtension(ext, new Object[] { actionSets[i] });
        }
        actionSetId = "org.eclipse.ui.actionSet.openFiles"; //$NON-NLS-1$
        for (int i = 0; i <actionSets.length; i++){
            if (!actionSets[i].getId().equals(actionSetId))
                continue;
            IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension();
           reg.removeExtension(ext, new Object[] { actionSets[i] });
        }
    }

    @Override
	protected void makeActions(final IWorkbenchWindow window) {
        // Creates the actions and registers them.
        // Registering is needed to ensure that key bindings work.
        // The corresponding commands keybindings are defined in the plugin.xml file.
        // Registering also provides automatic disposal of the actions when
        // the window is closed.

        exitAction = ActionFactory.QUIT.create(window);
        register(exitAction);
        
        saveAction = ActionFactory.SAVE.create(window);
        register(saveAction);
        
        saveAsAction = ActionFactory.SAVE_AS.create(window);
        register(saveAsAction);
        
        aboutAction = ActionFactory.ABOUT.create(window);
        register(aboutAction);
        
        
        
//        newWindowAction = ActionFactory.OPEN_NEW_WINDOW.create(window);
//        register(newWindowAction);
        
        addFileAction = new AddFileAction(window, "Add File to Corpus...", CorpusNavigationView.ID);
        register(addFileAction);
        
        newCorpusAction = new NewCorpusAction(window, "New Corpus", CorpusNavigationView.ID);
        register(newCorpusAction);
        
        deleteCorpusAction = new DeleteCorpusAction(window, "Delete Corpus", CorpusNavigationView.ID);
        register(deleteCorpusAction);

        createFolderAction = new CreateFolderAction(window, "Create New Folder", CorpusNavigationView.ID);
        register(createFolderAction);
        
        deleteFileAction = new DeleteFileAction(window, "Delete File/Folder", CorpusNavigationView.ID);
        register(deleteFileAction);
        
        renameFileAction=new RenameFileAction(window,"     Rename",CorpusNavigationView.ID);
       register(renameFileAction);
        
        applyFilterAction = new ApplyFilterAction(window, "Replayable from filter...", ReplayableTabularViewer.ID, CorpusNavigationView.ID);
        register(applyFilterAction);
        
        createReplayableAction = new CreateReplayableAction(window, "Replayable from scratch", ReplayableTabularEditor.ID, CorpusNavigationView.ID);
        register(createReplayableAction);
        
        newAnalysisActions = new Vector<IAction>();
        
        //navigationViewContingentActions
        
		try {
			IConfigurationElement[] config = Platform.getExtensionRegistry()
					.getConfigurationElementsFor("fr.emse.tatiana.analysis");
			for (IConfigurationElement e : config) {
				Object o = e.createExecutableExtension("analysisActivator");
				if (o instanceof IAnalysisActivator) {
					List<IAction> actions = ((IAnalysisActivator) o).getNewAnalysisActions(window, CorpusNavigationView.ID);
					for (IAction action : actions) {
						newAnalysisActions.add(action);
						navigationViewContingentActions.add(action);
						register(action);
					}
				}
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

        newVisualisationActions = new Vector<IAction>();
		try {
			IConfigurationElement[] config = Platform.getExtensionRegistry()
					.getConfigurationElementsFor("fr.emse.tatiana.visualisation");
			for (IConfigurationElement e : config) {
				Object o = e.createExecutableExtension("visualisationActivator");
				if (o instanceof IVisualisationActivator) {
					List<IAction> actions = ((IVisualisationActivator) o).getNewVisualisationActions(window, CorpusNavigationView.ID);
					for (IAction action : actions) {
						newVisualisationActions.add(action);
						replayableSelectedContingentActions.add(action);
						register(action);
					}
				}
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
        
        
        newGraphAction = new NewGraphAnalysisAction(window, "Graph", GraphAnalysisEditor.ID, CorpusNavigationView.ID);
        register(newGraphAction);
        
        
  
        
        importAction = new ImportAction(window, "Import...",CorpusNavigationView.ID);
        register(importAction);
        exportAction = new ExportAction(window, "Export (sub-)corpus...",CorpusNavigationView.ID);
        tatianaExportAction = new TatianaExportAction(window, "Export other...");
        register (tatianaExportAction);
        register(exportAction);
    }
    
    @Override
	protected void fillMenuBar(IMenuManager menuBar) {
    	MenuManager fileMenu = new MenuManager("&File", IWorkbenchActionConstants.M_FILE);
        MenuManager helpMenu = new MenuManager("&Help", IWorkbenchActionConstants.M_HELP);
        menuBar.add(fileMenu);
        // Add a group marker indicating where action set menus will appear.
        menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        menuBar.add(helpMenu);
        final MenuManager newreplayable = new MenuManager("New Replayable");
        newreplayable.add(applyFilterAction);
        newreplayable.add(createReplayableAction);
        final MenuManager newanalysis = new MenuManager("New Analysis");
        //newanalysis.add(newAnnotationAnalysisAction); // removed in ext pt creation
        newanalysis.add(newGraphAction);
        for (IAction action : newAnalysisActions) {
        	newanalysis.add(action);
        }
        
        final MenuManager newvisualisation = new MenuManager("Visualise as");
        for (IAction action : newVisualisationActions) {
        	newvisualisation.add(action);
        }
        
        // File
//        fileMenu.add(newWindowAction);
//        fileMenu.add(new Separator());
        fileMenu.add(newCorpusAction);
        fileMenu.add(new Separator());
       // fileMenu.add(createFolderAction);
       // fileMenu.add(deleteFileAction);
        fileMenu.add(addFileAction);
       // fileMenu.add(renameFileAction);
        fileMenu.add(new Separator());
        fileMenu.add(newreplayable);
        fileMenu.add(newanalysis);
        fileMenu.add(newvisualisation);
        fileMenu.add(new Separator());
        fileMenu.add(saveAction);
        fileMenu.add(saveAsAction);
        fileMenu.add(new MenuManager("Export to",TatianaConstants.M_EXPORT_ACTION));
        fileMenu.add(new Separator());
        
        fileMenu.add(importAction);
        fileMenu.add(exportAction);
        fileMenu.add(tatianaExportAction);
        fileMenu.add(deleteCorpusAction);
        fileMenu.add(new Separator());
        fileMenu.add(exitAction);
        
        // Help
        helpMenu.add(aboutAction);

    }
    
    @Override
	protected void fillCoolBar(ICoolBarManager coolBar) {
//        IToolBarManager toolbar = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
//        coolBar.add(new ToolBarContributionItem(toolbar, "main"));   
//        toolbar.add(openViewAction);
//        toolbar.add(messagePopupAction);
    }
}
